import { getCollection } from "astro:content";
import { type NavItem, articleNavList } from "@/constants/nav";

// 从文件名 2-xxx 解析 sort
function getSort(fileName?: string) {
  let sort = 999;
  if (!fileName) return sort;
  const splitArr: any[] = fileName.split("-");
  if (splitArr?.length && !isNaN(splitArr[0])) {
    sort = Number(splitArr[0]);
  }
  return sort;
}

// 从文件名 2-xxx 解析 title
function getTitle(fileName: string, entry: any) {
  let title = entry.data.title;
  if (title) return title;
  const splitArr: any[] = fileName.split("-");
  if (splitArr?.length) {
    title = splitArr.slice(1).join("-");
  }
  return title;
}

/**
 * 解析文档目录添加到 docList 中
 * 默认支持 3 级目录
 * 如果文件名是 readme.md 则不会显示在目录中，并且把 readme 的链接放在父级文件夹上
 * @param entry
 * @param docList
 */
function parseEntry(entry: any, docList: NavItem[]) {
  const slug = entry.slug;
  const slugArr: string[] = slug.split("/");
  const title = getTitle(slugArr[slugArr.length - 1], entry);
  const sort = getSort(slugArr[slugArr.length - 1]);
  if (slugArr.length === 1) {
    docList.push({
      text: title,
      href: slug,
      sort,
      children: [],
    });
  } else if (slugArr.length === 2) {
    const parent = slugArr[0];
    const isReadme = slugArr[1].toLowerCase() === "readme";
    const parentItem = docList.find(
      (item) => item.text.toLowerCase() === parent.toLowerCase()
    );
    if (parentItem) {
      if (isReadme) {
        parentItem.href = slug;
      } else {
        parentItem.children.push({
          text: title,
          href: slug,
          sort,
          children: [],
        });
      }
    } else {
      if (isReadme) {
        docList.push({
          text: parent,
          href: slug,
          sort,
          children: [],
        });
      } else {
        docList.push({
          text: parent,
          href: "#",
          sort,
          children: [
            {
              text: title,
              href: slug,
              sort,
              children: [],
            },
          ],
        });
      }
    }
  } else if (slugArr.length === 3) {
    const isReadme = slugArr[2].toLowerCase() === "readme";
    const grand = slugArr[0]; // 爷爷
    const grandItem = docList.find(
      (item) => item.text.toLowerCase() === grand.toLowerCase()
    );
    if (grandItem) {
      const parent = slugArr[1];
      const parentItem = grandItem.children.find(
        (item) => item.text.toLowerCase() === parent.toLowerCase()
      );
      if (parentItem) {
        if (isReadme) {
          parentItem.href = slug;
        } else {
          parentItem.children.push({
            text: title,
            href: slug,
            sort,
            children: [],
          });
        }
      } else {
        if (isReadme) {
          grandItem.children.push({
            text: parent,
            href: slug,
            sort,
            children: [],
          });
        } else {
          grandItem.children.push({
            text: parent,
            href: "#",
            sort,
            children: [
              {
                text: title,
                href: slug,
                sort,
                children: [],
              },
            ],
          });
        }
      }
    } else {
      if (isReadme) {
        docList.push({
          text: grand,
          href: "#",
          sort,
          children: [
            {
              text: slugArr[1],
              href: slug,
              sort,
              children: [],
            },
          ],
        });
      } else {
        docList.push({
          text: grand,
          href: "#",
          sort,
          children: [
            {
              text: slugArr[1],
              href: "#",
              sort,
              children: [
                {
                  text: title,
                  href: slug,
                  sort,
                  children: [],
                },
              ],
            },
          ],
        });
      }
    }
  }
}

// 收集文档列表
export async function collectDocList() {
  const docList: NavItem[] = JSON.parse(JSON.stringify(articleNavList));
  const docsEntries = await getCollection("docs");
  docsEntries.forEach((entry) => {
    parseEntry(entry, docList);
  });
  // 对 docList 进行递归排序
  function sortChildren(children: NavItem[]) {
    for (const child of children) {
      if (child.children?.length) {
        child.children = sortChildren(child.children);
      }
    }
    return children.sort((a, b) => a.sort! - b.sort!);
  }
  sortChildren(docList); // 对 docList 进行递归排序
  return docList;
}

// 笔记链接基础路径
export const baseDocPath = `/article/`;

// 收集面包屑列表，要获取当前路由对应的 title 名称
export async function collectCrumbList(slug: string) {
  const crumbs = [{ text: "笔记", href: baseDocPath }];
  const docsEntries = await getCollection("docs");
  // 如果 slug 包含 readme.md 则需要去掉
  if (slug.toLowerCase().endsWith("/readme")) {
    slug = slug.split("/").slice(0, -1).join("/");
  }
  slug.split("/").forEach((item, index) => {
    const path = slug
      .split("/")
      .slice(0, index + 1)
      .join("/");
    // 需要处理 readme.md 文件
    const entry = docsEntries.find(
      (entry) =>
        entry.slug === path ||
        entry.slug.toLowerCase() === `${path}/readme`.toLowerCase()
    );
    if (entry) {
      const title = entry.data.title || item;
      crumbs.push({
        text: title,
        href: baseDocPath + entry.slug,
      });
    } else {
      crumbs.push({
        text: item,
        href: "#",
      });
    }
  });
  return crumbs;
}
